import {Component, EventEmitter, OnInit, Output, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {FormObjModel} from '../formObj.model';
import {PUblicMethod} from '../../services/PUblicMethod';
import {ActivatedRoute, Router} from '@angular/router';
import {UndershelfObjModel} from '../undershelfObj.model';
import {TimeNotSameValidator} from '../../validator/validators';
import {PublicService} from '../../services/public.service';
import {BasicSelectedTableComponent} from '../public/basic-selected-table/basic-selected-table.component';
import {SelectEquipmentsComponent} from '../../public/select-equipments/select-equipments.component';
import {UnderShelfService} from '../under-shelf.service';
import {BasePage} from '../../base.page';
import {MessageService} from 'primeng/components/common/messageservice';
import {ConfirmationService} from 'primeng/api';

@Component({
  selector: 'app-create-note',
  templateUrl: './create-note.component.html',
  styleUrls: ['./create-note.component.scss']
})
export class CreateNoteComponent  extends BasePage implements OnInit {

    @ViewChild('basicSelectedTable') basicSelectedTable: BasicSelectedTableComponent;
    @ViewChild('selectEquipments') selectEquipments: SelectEquipmentsComponent;

    controlDiaglog: boolean;
    formTitle = '创建申请单';
    myForm: FormGroup;
    formObj: UndershelfObjModel;
    allTypes: Array<object>;
    approval: Array<object>;
    zh: any;


    displayPersonel: boolean = false;              // 人员组织组件是否显示

    constructor(private fb: FormBuilder,
                private router: Router,
                public messageService: MessageService,
                public confirmationService: ConfirmationService,
                private underShelfService: UnderShelfService,
                private publicService: PublicService,
                private activedRouter: ActivatedRoute) {
    super(confirmationService, messageService);
    this.allTypes = [
            {
                'label': '到期下架',
                'value': '到期下架'
            },
            {
                'label': '故障下架',
                'value': '故障下架'
            },
            {
                'label': '报废下架',
                'value': '报废下架'
            },
            {
                'label': '其他',
                'value': '其他'
            }

        ];
    }

    ngOnInit() {
        this.formObj = new UndershelfObjModel();
        this.zh = new PUblicMethod().initZh();
        this.initMyForm();
        this.formObj.plantime_begin = PUblicMethod.formateEnrtyTime(new Date());
        this.formObj.plantime_end = PUblicMethod.formateEnrtyTime(new Date());
        this.getApprovals('');
        this.formObj.unshelve_type = this.allTypes[0]['value'];
        this.controlDiaglog = false;
    }
    initMyForm = () =>  {
        this.myForm = this.fb.group({
            timeGroup: this.fb.group({
                plan_time_begin: [null, Validators.required],
                plan_time_end: [null, Validators.required]
            }, {validator: TimeNotSameValidator}),
            unshelve_reason: [null, Validators.required],
            applicant: [null, Validators.required],
            applicant_org: [null, Validators.required]
        });
    };

    getApprovals = (oid?) => {
        this.publicService.getApprovers(oid).subscribe(res => {
            if (!res) {
                this.approval = [];
            }else {
                let newArray = PUblicMethod.formateDepDropDown(res);
                this.approval = newArray;
                this.formObj.approve = newArray[0]['value']['name'];
                this.formObj.approve_pid = newArray[0]['value']['pid'];
                this.formObj.approve_org = newArray[0]['value']['post'];
                this.formObj.applicant_org_oid = newArray[0]['value']['oid'];
            }
            this.getQueryParams();
        });
    };

    goBack = () => {
        this.router.navigate(['../undershelfOverview'], {relativeTo: this.activedRouter});
    };

    openEquipList = () =>  {
        this.controlDiaglog = true;
    };

    dcontrolDialogHandler(event) {
        this.controlDiaglog = event;
    }
    startTimeSelected() {

    }

    getQueryParams = () => {
        this.activedRouter.queryParams.subscribe(params =>  {
            (params['sid'])  && this.requestMesageBySid(params['sid']);
        });
    };

    requestMesageBySid = id => {
        this.underShelfService.getMesageBySid(id).subscribe(res => {
            if (res['errcode'] === '00000') {
                this.formObj = new UndershelfObjModel(res['data']);
                // (res['data']['approver_pid']) && this.filterSelectedApporve(this.allApprovals, res['data']['approver_pid']);
                res['data']['devices'] ? this.basicSelectedTable.tableDatas = res['data']['devices'] : this.basicSelectedTable.tableDatas = [];
                (res['data']['devices'] && res['data']['devices']['length'] > 0) && this.getSelectedAnoArray(res['data']['devices']);
            }else {
                this.alert(`获取出入单信息失败 + ${res['errmsg']}`, 'error');
            }
        });
    };


    showPersonDialog = () => {this.displayPersonel = true; };

    clearPersonDialog = () => {
        this.formObj.applicant = '';
        this.formObj.applicant_org_oid = '';
        this.formObj.applicant_org = '';
        this.formObj.applicant_pid = '';
    };

    dataEmitter = event => {
        this.formObj.applicant = event.name;
        this.formObj.applicant_pid = event.pid;
        this.formObj.applicant_org = event.organization;
        this.formObj.applicant_org_oid = event.oid;
    };

    displayEmitter = event => { this.displayPersonel = event; };

    selectedEquipsEmitter = event => {
        event.forEach(arrayItem => {
            this.basicSelectedTable.tableDatas.push(arrayItem);
        });
        this.selectEquipments.searchObj.filter_anos = this.getSelectedAnoArray(this.basicSelectedTable.tableDatas);
    };

    getSelectedAnoArray = (data): any => {
        let anoArray = [];
        for (let i = 0; i < data.length; i++ ) {
            anoArray.push(data[i]['ano']);
        }
        return anoArray;
    }

    removeEquipmenst = () => {
        for (let i = 0; i < this.basicSelectedTable.selectedCars3.length; i++) {
            this.basicSelectedTable.tableDatas = this.basicSelectedTable.tableDatas.filter(v => {
                return !(v['ano'] === this.basicSelectedTable.selectedCars3[i]['ano']);
            })
        }
        this.selectEquipments.searchObj.filter_anos = this.getSelectedAnoArray(this.basicSelectedTable.tableDatas);
    };

    isFieldValid = (name) => {
        return PUblicMethod.isFieldValid(this.myForm, name);
    };

    // can listen fromgroup's error when formgroup nested formgroup
    isFieldFroupValid = (name?) => {
        return this.myForm.get('timeGroup').hasError('timematch');
    };

    // for button which is relative with one of formcontrol
    isFieldValueValid = (name) => {
        return PUblicMethod.isFieldValueValid(this.myForm, name);
    };

    // formgroup nested formgroup can use this
    isFieldGroupItemValid = (name) => {
        return PUblicMethod.isFieldGroupValid(this.myForm.get('timeGroup'), name);
    };

    save = () => {
        this.formatPerson();
        this.formatTime();
        this.formObj.devices = this.basicSelectedTable.tableDatas;
        (!this.formObj.sid) && (this.requestSave());
        (this.formObj.sid) && (this.requestSaveAfterEdited());
    };

    formatPerson = () => {
        if (typeof this.formObj.approve === 'object') {
            this.formObj.approve_pid = this.formObj.approve['pid'];
            this.formObj.approve = this.formObj.approve['name'];
        }
    };

    formatTime = () => {
        this.formObj.plantime_begin = PUblicMethod.formateEnrtyTime(this.formObj.plantime_begin);
        this.formObj.plantime_end = PUblicMethod.formateEnrtyTime(this.formObj.plantime_end);
    };

    requestSave = () => {
        this.underShelfService.requestSave(this.formObj).subscribe(res => {
            if ( res === '00000' ) {
                this.alert('保存成功')
                window.setTimeout(() => {
                    this.goBack();
                }, 1100);
            }else {
                this.alert(`保存失败 + ${res}`, 'error');
            }
        });
    };

    requestSaveAfterEdited = () => {
        this.underShelfService.requestSaveAfterEdited(this.formObj).subscribe(res => {
            if ( res === '00000' ) {
                this.alert('修改保存成功')
                window.setTimeout(() => {
                    this.goBack();
                }, 1100);
            }else {
                this.alert(`修改保存失败 + ${res}`, 'error');
            }
        });
    };

    submit = () => {
        this.formatPerson();
        this.formatTime();
        this.formObj.devices = this.basicSelectedTable.tableDatas;
        if (this.myForm.valid) {
            if (this.formObj.devices.length === 0) {
                this.alert('请先选择设备再进行提交', 'warn');
            }else {
                (!this.formObj.sid) && (this.requestSubmit());
                (this.formObj.sid) && (this.requestSubmitAfterEidted());
            }
        }else {
            PUblicMethod.validateAllFormFields(this.myForm);
        }
    };

    requestSubmitAfterEidted = () => {
        this.underShelfService.requestSubmitAfterEdit(this.formObj).subscribe(res => {
            if ( res === '00000' ) {
                this.alert('修改提交成功')
                window.setTimeout(() => {
                    this.goBack();
                }, 1100);
            }else {
                this.alert(`修改提交失败 + ${res}`, 'error');
            }
        });
    };

    requestSubmit = () => {
        this.underShelfService.requestSubmite(this.formObj).subscribe(res => {
            if ( res === '00000' ) {
                this.alert('提交成功');
                window.setTimeout(() => {
                    this.goBack();
                }, 1100);
            }else {
                this.alert(`提交失败失败 + ${res}`, 'error');
            }
        });
    };

}
